<template>
  <div :class="['message', role]">
    <div class="message-content">
      <div class="avatar">
        <img :src="avatarSrc" :alt="role">
      </div>
      <div class="text-content">
        <div class="message-text" v-html="compiledMarkdown"></div>
        <div class="timestamp">{{ formattedTime }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
// 使用marked的具名导入方式并禁用解析安全限制
import * as marked from 'marked'

// 设置marked解析选项
marked.setOptions({
  gfm: true,
  tables: true,
  breaks: false,
  pedantic: false,
  sanitize: false,
  smartLists: true,
  smartypants: false
})

const props = defineProps({
  role: {
    type: String,
    required: true,
    validator: (value) => ['user', 'assistant'].includes(value)
  },
  content: {
    type: String,
    required: true
  },
  timestamp: {
    type: String,
    required: true
  }
})

const avatarSrc = computed(() => {
  return props.role === 'user' 
    ? '/user-avatar.png'  // 确保在public目录中添加这些图片
    : '/ai-avatar.png'
})

const formattedTime = computed(() => {
  const date = new Date(props.timestamp)
  return date.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
})

// 将markdown转换为HTML
const compiledMarkdown = computed(() => {
  if (!props.content) {
    return ''
  }
  return marked.parse(props.content)
})
</script>

<style scoped>
.message {
  display: flex;
  margin: 1rem 0;
  padding: 0.5rem;
  max-width: 80%;
}

.message.user {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message.assistant {
  margin-right: auto;
}

.message-content {
  display: flex;
  gap: 1rem;
  align-items: flex-start;
}

.user .message-content {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.text-content {
  background-color: #f0f0f0;
  padding: 0.8rem;
  border-radius: 1rem;
  position: relative;
  max-width: 600px;
}

.user .text-content {
  background-color: #007AFF;
  color: white;
}

.message-text {
  white-space: pre-wrap;
  word-break: break-word;
}

.timestamp {
  font-size: 0.75rem;
  color: #666;
  margin-top: 0.25rem;
}

.user .timestamp {
  color: rgba(255, 255, 255, 0.8);
}

@media (max-width: 768px) {
  .message {
    max-width: 90%;
  }
  
  .text-content {
    max-width: calc(100vw - 120px);
  }
}
</style>